<?php

require_once (APPLICATION_PATH . '/../library/phpthumblib/ThumbLib.inc.php');

class QuotationController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'quotation', '');
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "";
        $searchtype = "";
        $searchtext = "";
        $datefrom = '';
        $dateto = '';
        $orderField = 'qn_id';
        $sort = 'asc';

        /* Pagination Login */
        $itemsPerPageReviews = $this->config->PAGING_PER_PAGE;
        $currentPageReviews = 1;

        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }


        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();

            //Multiple Delete Logic
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = "Please select atleast one checkbox";
                }
            }

            /* Search Facility Over Here */
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                if ($searchtype == "cus_name" ||
                        $searchtype == "qn_id" ||
                        $searchtype == "qn_name" ||
                        $searchtype == "lgn_email" ||
                        $searchtype == "cus_name") {
                    $searchtext = $postedData["searchtext"];
                    if ($searchtext == '') {
                        $errorMessage[] = "Please enter search text for search.";
                    } else {
                        $where = "$searchtype LIKE '%$searchtext%'";
                    }
                } else if ($searchtype == 'daterange') {
                    $booldate = false;
                    $datefrom = $postedData['datefrom'];
                    $dateto = $postedData['dateto'];

                    if (GTL_Common::IsEmpty($datefrom)) {
                        $errorMessage[] = 'Please enter from date.';
                    } else if (!GTL_Common::IsValidDate($datefrom)) {
                        $errorMessage[] = 'Please enter proper from date in YYYY-MM-DD.';
                    } else {
                        $booldate = true;
                    }

                    if (GTL_Common::IsEmpty($dateto)) {
                        $errorMessage[] = 'Please enter to date.';
                        $booldate = false;
                    } else if (!GTL_Common::IsValidDate($dateto)) {
                        $errorMessage[] = 'Please enter proper to date in YYYY-MM-DD.';
                        $booldate = false;
                    } else {
                        $booldate = true;
                    }

                    if ($booldate) {
                        $where = "qn_created BETWEEN  '" . $datefrom . "' AND '" . $dateto . "  23:59:59" . "' ";
                    }
                }
            }
        }

        $quotationModel = new Model_Quotation();
        $quotationsData = $quotationModel->fetchQuotations($where, $itemsPerPageReviews, $offset, $orderField, $sort);

        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($quotationModel->getQuotationCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'quotation', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->quotationsData = $quotationsData;

        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;

        $this->view->searchtype = $searchtype;
        $this->view->searchtext = $searchtext;
        $this->view->datefrom = $datefrom;
        $this->view->dateto = $dateto;

        $indexUrl = $this->view->url(array('controller' => 'index', 'action' => 'index'), null, TRUE);
        $quotationUrl = $this->view->url(array('controller' => 'quotation', 'action' => 'list'), null, TRUE);
        $this->view->breadcrumbs = array($indexUrl => "Home", $quotationUrl => "Quotation", "" => "Quotation Listing");
    }

    public function formAction() {
        //Initialize View variables
        $customers = Array();
        $quotation = Array();
        $quotationImages = Array();
        $quotationReference = Array();
        $qnr_ids = Array();


        //Load Admin Model
        $adminModel = new Model_Admin();
        $adminData = $adminModel->fetchEntryById('1');
        $this->view->adminData = $adminData;

        //Load Category Model 
        $categoryModel = new Model_Category();
        $categoryArray = $categoryModel->getCategoryArray(false);
        $this->view->categoryArray = $categoryArray;

        $categories = $categoryModel->fetchCategorys();
        foreach ($categories as $_cat) {
            $allCategories[$_cat['cat_id']] = $_cat;
        }
        $this->view->allCategories = $allCategories;

        //Load the quotation Model
        $customerModel = new Model_Customer();
        $customerArray = $customerModel->fetchCustomers("lgn.lgn_active = '1'");
        if (count($customerArray) > 0) {
            foreach ($customerArray as $_customer) {
                $customers[$_customer['cus_id']] = $_customer['cus_name'];
            }
        }


        //Check for the quotation Parameter
        $projectData['qn_id'] = $this->_request->getParam('qn_id');
        $qn_id = (!empty($projectData['qn_id'])) ? $projectData['qn_id'] : null;


        $this->view->mode = "Add";
        if (!empty($qn_id)) {
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            //Load Quotation Model
            $quotationModel = new Model_Quotation();
            $dataArray = $quotationModel->fetchEntryById($qn_id);
            $quotation = $dataArray['QUOTATION'];
            $quotationReference = $dataArray['QUOTATION_REFERENCE'];
            $quotationImages = $dataArray['QUOTATION_IMAGES'];
            foreach ($quotationReference as $_ref) {
                $qnr_ids[$_ref['qnr_id']] = $_ref['qnr_id'];
            }
        }

        $this->view->quotation = $quotation;
        $this->view->quotationImages = $quotationImages;
        $this->view->quotationReference = $quotationReference;


        
        $finalQREfArray = Array();
        foreach ($quotationReference as $_qref) {
            //Category Is is not blank
            $category = $_qref['qnr_cat_id'];
            $sub_category = $_qref['qnr_sub_cat_id'];
            
            if ( $category != '') {
                if ($sub_category == '') {
                    $finalQREfArray[$category]['data'][$category][] = $_qref;
                    #$key = "blank_".rand(1000,2000);
                    #$finalQREfArray[$key] = $_qref;
                } else {
                    
                    $finalQREfArray[$category]['subcategory'][$sub_category][] =  $_qref;
                }
            } else {
                $key = "blank_".rand(1,1000);
                $finalQREfArray[$key] = $_qref;
            }
        }
        
        $this->view->finalQREfArray = $finalQREfArray;
        
        #echo "<pre>";
        #print_r($finalQREfArray);
        #exit;


        if ($this->_request->isPost()) {

            $postedData = $this->_request->getPost();

            //Initialize Quotation data
            $quotationData = Array();
            $quotationData['qn_name'] = $postedData['qn_name'];
            $quotationData['qn_id'] = $qn_id;
            if ($postedData['cus_id'] == "") {
                $quotationData['cus_id'] = "";
                $quotationData['cus_name'] = "";
            } else {
                $quotationData['cus_id'] = $postedData['cus_id'];
                $quotationData['cus_name'] = $customers[$postedData['cus_id']];
            }
            $quotationData['qn_description'] = "";
            $quotationData['qn_costprice'] = GTL_Common::setNumberFormat($postedData['qn_costprice']);
            $quotationData['qn_sellingprice'] = GTL_Common::setNumberFormat($postedData['qn_sellingprice']);
            $quotationData['qn_profit_loss_margin'] = GTL_Common::setNumberFormat($postedData['qn_profit_loss_margin']);
            $quotationData['qn_created'] = date('Y-m-d H:i:s');

            //Load Quotation Model
            $quotationModel = new Model_Quotation();
            $qn_id = $quotationModel->save($quotationData, 'qn_id');

            //Load Quotation Reference Table
            $quotationRefModel = new Model_Quotationreference();

            //Delete the Quotation Reference deleted fields 
            if ($postedData['hdn_delete_qnrids'] != '') {
                $deleteQnRefids = $postedData['hdn_delete_qnrids'];
                $quotationRefModel->delete("qnr_id in (" . $deleteQnRefids . ")");
            }


            //Initialize Quotation Reference Data
            $qnr_typeData = $postedData['type'];
            $qnr_ref_idData = $postedData['inventorylist'];
            $qnr_qtyData = $postedData['qty'];
            $qnr_materialcostData = $postedData['cost'];
            $qnr_materialsrpData = $postedData['srp'];
            $qnr_uomData = $postedData['uom'];
            $qnr_categoryData = $postedData['category'];
            $qnr_subcategoryData = $postedData['sub_category'];
            $qnr_totalmaterialcostData = $postedData['totalcost'];
            $qnr_totalmaterialsrpData = $postedData['totalsrp'];
            $qnr_nameData = $postedData['product_material_code'];
            $qnr_descriptionData = $postedData['qnr_description'];
            $qnr_idData = $postedData['qnr_id'];

            $i = 0;
            foreach ($qnr_typeData as $type) {
                $quotationData = Array();

                if ($qnr_idData[$i] == '') {
                    $qnr_id = null;
                } else {
                    $qnr_id = $qnr_idData[$i];
                }

                $quotationData['qnr_id'] = $qnr_id;
                $quotationData['qnr_type'] = $type;
                $quotationData['qn_id'] = $qn_id;
                $quotationData['qnr_ref_id'] = $qnr_ref_idData[$i];
                $quotationData['qnr_name'] = $qnr_nameData[$i];
                $quotationData['qnr_cat_id'] = $qnr_categoryData[$i];
                $quotationData['qnr_sub_cat_id'] = $qnr_subcategoryData[$i];
                $quotationData['qnr_qty'] = $qnr_qtyData[$i];
                $quotationData['qnr_uom'] = $qnr_uomData[$i];
                $quotationData['qnr_materialcost'] = GTL_Common::setNumberFormat($qnr_materialcostData[$i]);
                $quotationData['qnr_materialsrp'] = GTL_Common::setNumberFormat($qnr_materialsrpData[$i]);
                $quotationData['qnr_totalmaterialcost'] = GTL_Common::setNumberFormat($qnr_totalmaterialcostData[$i]);
                $quotationData['qnr_totalmaterialsrp'] = GTL_Common::setNumberFormat($qnr_totalmaterialsrpData[$i]);
                $quotationData['qnr_description'] = $qnr_descriptionData[$i];
                $quotationRefModel->save($quotationData, 'qnr_id');
                $i++;
            }

            //Load Quotation Image Model
            $quotationImageModel = new Model_Quotationimages();

            //Multiple Quotation Image Upload Logic
            $upload = new Zend_File_Transfer_Adapter_Http();
            $k = 0;
            foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
                if ($asFileInfo['name'] != '') {
                    $fileName = '';

                    $folder = $this->config->UPLOAD_PATH . "quotation/";
                    $upload->setDestination($folder);
                    $originalFilename = pathinfo($asFileInfo['name']);

                    $fileName = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                    $upload->addFilter('Rename', $fileName, 'filename');
                    $upload->receive($fields);

                    $thumb2 = PhpThumbFactory::create($folder . $fileName);
                    $thumb2->resize(200, 200);
                    $thumb2->save($folder . '/' . 'thumb_' . $fileName, 'jpg');

                    $imageNotes = ($postedData['qni_desc'][$k] == '') ? '' : $postedData['qni_desc'][$k];
                    $quotationImageData = Array();
                    $quotationImageData['qn_id'] = $qn_id;
                    $quotationImageData['qni_image'] = $fileName;
                    $quotationImageData['qni_desc'] = $imageNotes;
                    $quotationImageModel->save($quotationImageData, 'qni_id');
                }
                $k++;
            }

            $successmessage = "Quotation generated successfully";
            $this->addSuccessMessage($successmessage);
            //$this->_helper->redirector('list', 'quotation', '');
            $this->_helper->redirector('form', 'quotation', '', array('qn_id' => $qn_id));
        }


        $this->view->customers = $customers;
    }

    //Function to give the select list of the products and jobs for ajax purpose
    public function generateinventorylistAction() {
        $listString = "";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            if ($postedData['type'] == 'job') {
                $jobModel = new Model_Job();
                $jobArray = $jobModel->fetchJobs("job_status = 'active'");
                if (count($jobArray) > 0) {
                    $listString = "<option value=''>-- Select Job --</option>";
                    foreach ($jobArray as $_job) {
                        $listString .= "<option value='" . $_job['job_id'] . "'>" . $_job['job_code'] . "</option>";
                    }
                }
            } else {
                $productModel = new Model_Product();
                $productArray = $productModel->fetchProducts("prd_status = 'active'");
                if (count($productArray) > 0) {
                    $listString = "<option value=''>-- Select product --</option>";
                    foreach ($productArray as $_product) {
                        $listString .= "<option value='" . $_product['prd_id'] . "'>" . $_product['prd_code'] . "</option>";
                    }
                }
            }
        }
        echo $listString;
        exit;
    }

    //Function to give the data of individual products and job for jax purpose
    public function generateproductitemAction() {
        $returnArray = Array(
            'COST_PRICE' => '0.00',
            'SELLING_PRICE' => '0.00',
            'PRODUCT_JOB_CODE' => ''
        );
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            if ($postedData['type'] == 'job') {
                $jobModel = new Model_Job();
                $jobArray = $jobModel->fetchEntryById($postedData['id']);
                if (count($jobArray) > 0) {
                    $costprice = $jobArray['job_materialcost'];
                    $sellingPrice = $jobArray['job_materialsrp'];
                    $code = $jobArray['job_code'];
                }
            } else {
                $productModel = new Model_Product();
                $productArray = $productModel->fetchEntryById($postedData['id']);
                if (count($productArray) > 0) {
                    $costprice = $productArray['prd_materialcost'];
                    $sellingPrice = $productArray['prd_materialsrp'];
                    $code = $productArray['prd_code'];
                }
            }
        }
        $returnArray = Array(
            'COST_PRICE' => $costprice,
            'SELLING_PRICE' => $sellingPrice,
            'PRODUCT_JOB_CODE' => $code
        );
        echo Zend_Json_Encoder::encode($returnArray);
        exit;
    }

    public function viewAction() {

        if ($this->_getParam('qn_id') && $this->_getParam('qn_id') != "") {

            //Load Admin Model
            $adminModel = new Model_Admin();
            $adminData = $adminModel->fetchEntryById('1');

            $qn_id = $this->_getParam('qn_id');

            //Load Quotation Model
            $quotationModel = new Model_Quotation();
            $dataArray = $quotationModel->fetchEntryById($qn_id);
            $quotation = $dataArray['QUOTATION'];
            $quotationReference = $dataArray['QUOTATION_REFERENCE'];
            $quotationImages = $dataArray['QUOTATION_IMAGES'];

            //Initialize View variables

            $this->view->adminData = $adminData;
            $this->view->quotations = $quotation;
            $this->view->quotationReference = $quotationReference;
            $this->view->quotationImages = $quotationImages;
        } else {
            $this->_helper->redirector('list', 'quotation', '');
        }
    }

    public function deleteAction($ids = Array()) {
        //Load Customer Model 
        $quotationModel = new Model_Quotation();

        if ($this->_getParam('qn_id') && $this->_getParam('qn_id') != "") {
            $qn_id = $this->_getParam('qn_id');
            $quotationModel->deleteQuotation(Array($qn_id));
            $this->addSuccessMessage("Quotation deleted succesfully");
            $this->_helper->redirector('list', 'quotation', '');
        } else {
            $quotationModel->deleteQuotation($ids);
            $this->addSuccessMessage("Quotation deleted succesfully");
            $this->_helper->redirector('list', 'quotation', '');
        }
    }

    //Function to give the data of individual products and job
    public function generateproductsearchAction() {
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            if ($postedData['type'] == 'job') {
                $job = Array(
                    'id' => '',
                    'code' => 'No such job available',
                    'uom' => '',
                    'costprice' => '0.00',
                    'srpprice' => '0.00'
                );
                $jobModel = new Model_Job();
                $jobArray = $jobModel->fetchJobs("`job_code` LIKE '%" . $postedData['search'] . "%'");
                $jsonArray = Array();
                if (count($jobArray) > 0) {
                    foreach ($jobArray as $_job) {
                        $job = Array(
                            'id' => $_job['job_id'],
                            'code' => $_job['job_code'],
                            'uom' => $_job['job_uom'],
                            'costprice' => $_job['job_materialcost'],
                            'srpprice' => $_job['job_materialsrp'],
                        );
                        $jsonArray[] = $job;
                    }
                } else {
                    $jsonArray[] = $job;
                }
                echo Zend_Json_Encoder::encode($jsonArray);
            } else {
                $product = Array(
                    'id' => '',
                    'code' => 'No such product available',
                    'uom' => '',
                    'costprice' => '0.00',
                    'srpprice' => '0.00'
                );
                $productModel = new Model_Product();
                $productArray = $productModel->fetchproducts("`prd_code` LIKE '%" . $postedData['search'] . "%'");
                $jsonArray = Array();
                if (count($productArray) > 0) {
                    foreach ($productArray as $_product) {
                        $product = Array(
                            'id' => $_product['prd_id'],
                            'code' => $_product['prd_code'],
                            'uom' => $_product['prd_uom'],
                            'costprice' => $_product['prd_materialcost'],
                            'srpprice' => $_product['prd_materialsrp'],
                        );
                        $jsonArray[] = $product;
                    }
                } else {
                    $jsonArray[] = $product;
                }
                echo Zend_Json_Encoder::encode($jsonArray);
            }
        }
        exit;
    }

    public function deletequotationimageAction() {

        if ($this->getRequest()->isPost()) {

            $postedData = $this->_request->getPost();
            $qni_id = $postedData['qni_id'];

            //Load Quotation Image Model
            $quotationImageModel = new Model_Quotationimages();
            $data = $quotationImageModel->fetchRow("qni_id = '" . $qni_id . "'");
            if ($data) {
                $quotationImageModel->delete("qni_id  = '" . $qni_id . "'");
                $folder = $this->config->UPLOAD_PATH . "quotation/";
                $image = $folder . $data->qni_image;
                $thumb_image = $folder . "thumb_" . $data->qni_image;
                if (file_exists($image)) {
                    @unlink($image);
                }
                if (file_exists($thumb_image)) {
                    @unlink($thumb_image);
                }
            }
        }
        exit;
    }

    public function getsubcategoryAction() {
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            $cat_parentid = $postedData['cat_parentid'];
            $cat_selected = $postedData['cat_selected'];
            if (trim($cat_parentid) == '') {
                $cat_parentid = '1#1';
            }
            $categoryModel = new Model_Category();
            $categoryArray = $categoryModel->fetchCategorys("cat_parentid = '" . $cat_parentid . "'");
            $catString = '';
            $selected = '';
            #$catString .= "<label for='modal_sub_cat'>Sub Category</label>";
            #$catString .= "<select id='modal_sub_cat' name='modal_sub_cat' class='text'>";
            $catString .= "<option value=''>  -- Select Sub Category --  </option>";
            foreach ($categoryArray as $_cat) {
                if ($cat_selected == $_cat['cat_id']) {
                    $selected = 'selected';
                }
                $catString .= "<option " . $selected . "  value='" . $_cat['cat_id'] . "'>" . $_cat['cat_name'] . "</option>";
            }
            #$catString .= "</select>";
            echo $catString;
            exit;
        }
    }

}

?>